<?php
declare (strict_types = 1);

namespace app\common\model\data;

use think\Exception;
use think\Model;

/**
 * @mixin think\Model
 */
class Garbage extends Model
{
    /**
     * 获取内容关联的文件大小
     */
    public static function getRelatedSize(){
        return static::getSize(config('app.related_dir'));
    }

    /**
     * 获取缓存目录大小
     */
    public static function getCacheSize(){
        return static::getSize(config('app.cache_dir'));
    }

    /**
     * 获取临时目录文件大小
     */
    public static function getGDSize(){
        return static::getSize(config('app.garbage_dir'));
    }

    /**
     * 获取目录的大小
     * @param $dirs array # 目录数组
     * @return string
     */
    private static function getSize(array $dirs){
        $size = 0;
        foreach ( $dirs as $dir){
            if (is_dir($dir)){
                $size += (int) static::getDirSize($dir);
            }
        }
        return round($size/1024/1024, 2) . 'M'; //四舍五入 保留2位小数
    }

    //获取文件夹大小
    private static function getDirSize($path) : int {

        $size = 0;

        if(is_file($path)){
            $size += filesize($path);
        }else{
            if(is_dir($path)){
                $data = scandir($path);
                if(!empty($data)){
                    foreach ($data as $value){
                        if($value != '.' && $value != '..'){
                            $sub_path = $path."/".$value;
                            $size += static::getDirSize($sub_path);
                        }
                    }

                }
            }
        }

        return $size;
    }

    /**
     * 清理垃圾
     * @return bool
     * @throws Exception
     */
    public static function clearGD(){
        $dirs = config('app.garbage_dir');
        if (!is_array($dirs)) throw new Exception('配置错误.');
        foreach ($dirs as $dir){
            if (is_dir($dir))
                static::clear($dir);
        }
        return true;
    }

    //删除目录
    private static function clear($dirname){
        if ( !is_dir($dirname) ) throw new Exception('配置错误.');

        $handler = opendir($dirname);
        while(($file = readdir($handler)) !== false){

            if ($file == '.' || $file == '..') continue;
            $dir = $dirname . '/' . $file;

            is_dir($dir) ? self::clear($dir) : unlink($dir);
        }
        closedir($handler);
        if (!rmdir($dirname)) throw new Exception('清理垃圾失败');
        return true;
    }



}
